<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" ref="queryForm" label-width="68px">
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="课程ID" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程ID"
          clearable
          size="small"
          style="width: 180px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="6">
        <el-card class="statistics-card">
          <div slot="header"><span>总互动次数</span></div>
          <div class="content">
            <div class="number">{{ totalCount }}</div>
            <div class="desc"><i class="el-icon-comments"></i> 累计参与课堂互动</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div slot="header"><span>获得积分</span></div>
          <div class="content">
            <div class="number">{{ totalScore }}</div>
            <div class="desc"><i class="el-icon-star-on"></i> 互动累计获得积分</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 互动类型统计图表 -->
    <el-card class="mb8">
      <div slot="header"><span>互动类型分布</span></div>
      <!-- 图表容器：永久渲染并设置固定宽高 -->
      <div class="chart-container">
        <div ref="typeChart" class="chart" style="width: 100%; height: 300px;"></div>
      </div>
      <!-- 降级表格：ECharts加载失败或无数据时显示 -->
      <div class="chart-fallback" v-show="!echartsLoaded || (echartsLoaded && !typeDistribution.length)">
        <el-table :data="typeDistribution" border stripe style="width: 100%;" v-if="typeDistribution.length">
          <el-table-column prop="typeName" label="互动类型" align="center"></el-table-column>
          <el-table-column prop="count" label="次数" align="center"></el-table-column>
          <el-table-column label="占比" align="center">
            <template slot-scope="scope">
              {{ ((scope.row.count / totalCount) * 100).toFixed(1) + "%" }}
            </template>
          </el-table-column>
        </el-table>
        <el-empty description="暂无互动类型统计数据" v-else></el-empty>
      </div>
    </el-card>

    <!-- 互动记录表格 -->
    <el-card>
      <div slot="header"><span>互动记录列表</span></div>
      <div v-if="showTable">
        <el-table
          v-loading="loading"
          :data="currentPageData"
          border
          stripe
          style="width: 100%;"
          :key="tableKey"
        >
          <el-table-column prop="courseName" label="课程名称" align="center"></el-table-column>
          <el-table-column label="互动类型" align="center">
            <template slot-scope="scope">
              <el-tag
                :class="`interaction-type-${scope.row.interactionType}`"
                size="mini"
              >
                {{ getInteractionTypeDesc(scope.row.interactionType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="interactionContent" label="互动内容" align="center"></el-table-column>
          <el-table-column prop="interactionTime" label="互动时间" align="center"></el-table-column>
          <el-table-column prop="scoreRewarded" label="获得积分" align="center"></el-table-column>
        </el-table>
      </div>
      <div v-else-if="!loading && total === 0" class="no-data">
        <el-empty description="暂无互动记录数据"></el-empty>
      </div>

      <!-- 分页组件 -->
      <el-pagination
        v-if="total > 0"
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
        style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
// 引入ECharts
import * as echarts from 'echarts';
// 引入API
import { 
  getMyInteractions, 
  getMyInteractionStatistics, 
  getMyInteractionsByTime, 
  getMyInteractionsByCourse 
} from "@/api/system/interaction";

export default {
  name: "Interaction",
  data() {
    return {
      loading: false,
      interactionList: [],
      currentPageData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      tableKey: 1,
      showTable: false,
      queryParams: {
        startTime: null,
        endTime: null,
        courseId: null
      },
      totalCount: 0,
      totalScore: 0,
      typeChart: null,
      echartsLoaded: !!echarts,
      typeDistribution: [],
      interactionTypeMap: {
        1: "提问",
        2: "回答",
        3: "讨论",
        4: "投票",
        5: "签到"
      }
    };
  },
  created() {
    this.getList();
    this.getStatistics();
  },
  mounted() {
    // 初始化图表（确保DOM已渲染）
    this.$nextTick(() => {
      this.initChart();
    });
    // 绑定窗口resize事件（添加passive优化）
    window.addEventListener("resize", this.handleResize, { passive: true });
  },
  beforeDestroy() {
    // 清理事件和图表实例
    window.removeEventListener("resize", this.handleResize);
    if (this.typeChart && echarts) {
      echarts.dispose(this.$refs.typeChart);
      this.typeChart = null;
    }
  },
  methods: {
    // 获取互动记录列表
    getList() {
      this.loading = true;
      this.showTable = false;
      let requestPromise;

      if (this.queryParams.courseId) {
        requestPromise = getMyInteractionsByCourse(this.queryParams.courseId);
      } else if (this.queryParams.startTime && this.queryParams.endTime) {
        requestPromise = getMyInteractionsByTime(
          this.queryParams.startTime,
          this.queryParams.endTime
        );
      } else {
        requestPromise = getMyInteractions();
      }

      requestPromise.then(response => {
        this.interactionList = response.data || [];
        this.total = this.interactionList.length;
        this.handlePageChange(this.currentPage);
        this.calculateTotalScore();
        this.$nextTick(() => {
          this.showTable = true;
        });
      }).catch(error => {
        this.$message.error("加载失败：" + (error.msg || error.message));
        this.interactionList = [];
        this.currentPageData = [];
        this.total = 0;
        this.showTable = false;
      }).finally(() => {
        this.loading = false;
      });
    },

    // 分页处理
    handlePageChange(page) {
      const startIndex = (page - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.currentPageData = this.interactionList.slice(startIndex, endIndex) || [];
    },

    // 获取统计数据
    getStatistics() {
      getMyInteractionStatistics().then(response => {
        const data = response.data || {};
        this.totalCount = data.totalCount || 0;
        this.typeDistribution = (data.typeDistribution || []).map(item => ({
          ...item,
          typeName: this.interactionTypeMap[item.interactionType] || "未知"
        }));
        this.updateChart();
      }).catch(error => {
        this.$message.error("统计数据加载失败：" + error.message);
        this.typeDistribution = [];
        this.totalCount = 0;
      });
    },

    // 计算总积分
    calculateTotalScore() {
      this.totalScore = this.interactionList.reduce((sum, item) => {
        return sum + (item.scoreRewarded || 0);
      }, 0);
    },

    // 初始化图表
    initChart() {
      if (!this.echartsLoaded || !this.$refs.typeChart) {
        console.warn("ECharts未加载或图表容器不存在");
        return;
      }

      // 检查是否已有实例，避免重复初始化
      const existingInstance = echarts.getInstanceByDom(this.$refs.typeChart);
      if (existingInstance) {
        this.typeChart = existingInstance;
      } else {
        this.typeChart = echarts.init(this.$refs.typeChart);
      }

      // 设置默认配置
      this.typeChart.setOption({
        tooltip: { trigger: "item" },
        legend: { orient: "horizontal", bottom: 0, data: [] },
        series: [{
          name: "互动类型",
          type: "pie",
          radius: ["40%", "70%"],
          data: [],
          label: { show: true, formatter: "{b}: {c} ({d}%)" }
        }]
      });

      this.updateChart();
    },

    // 更新图表数据
    updateChart() {
      if (!this.echartsLoaded || !this.typeChart || !this.typeDistribution.length) {
        return;
      }

      const chartData = this.typeDistribution.map(item => ({
        name: item.typeName,
        value: item.count || 0
      }));

      this.typeChart.setOption({
        legend: { data: chartData.map(item => item.name) },
        series: [{ data: chartData }]
      });
    },

    // 窗口大小变化时重绘图表
    handleResize() {
      if (this.echartsLoaded && this.typeChart) {
        this.typeChart.resize();
      }
    },

    // 查询
    handleQuery() {
      this.currentPage = 1;
      this.getList();
      this.getStatistics();
    },

    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.currentPage = 1;
      this.getList();
      this.getStatistics();
    },

    // 获取互动类型描述
    getInteractionTypeDesc(type) {
      return this.interactionTypeMap[type] || "未知";
    }
  }
};
</script>

<style scoped>
.statistics-card {
  transition: all 0.3s ease;
}
.statistics-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
.content {
  text-align: center;
  padding: 15px 0;
}
.number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #1890ff;
}
.desc {
  color: #666;
  font-size: 14px;
}

/* 图表容器样式 */
.chart-container {
  width: 100%;
  height: 300px;
  position: relative;
}
.chart-fallback {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

/* 无数据样式 */
.no-data {
  text-align: center;
  padding: 50px 0;
}

/* 互动类型标签样式 */
.interaction-type-1 { background-color: #4285f4; }
.interaction-type-2 { background-color: #0f9d58; }
.interaction-type-3 { background-color: #f4b400; }
.interaction-type-4 { background-color: #db4437; }
.interaction-type-5 { background-color: #9c27b0; }

.mb8 { margin-bottom: 8px; }
</style>
